import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TextInput,
  Image,
  TouchableWithoutFeedback,
  Dimensions,
  StyleSheet,
  Keyboard,
} from 'react-native';
import {
  ModalCreateGroup,
  FlatListTm,
  TitleBar,
  ModalSelectSticker,
} from '../components';
import StickerDataSQL from '../db';
import {DB_ST} from '../utils/DBFields';
import NativeFileUtils from 'rtn-supernote-plugin-core/src/module/NativeFileUtils';
import {renameFunGroup, saveSticker, stickerGroupAdd} from '../utils/StickerUtils';
import NativeEvent from 'rtn-supernote-plugin-core/src/module/NativeEvent';
import i18n from '../i18n';
import {findNextEm} from '../utils/jsUtils';

const StickerCreatePage = ({changeEvent}) => {
  const [stickerName, setStickerName] = useState('');
  const [stickerDefaultName, setStickerDefaultName] = useState('');
  const [stickerGroups, setStickerGroups] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalStickerVisible, setModalStickerVisible] = useState(false);
  const [stickerGroup, setStickerGroup] = useState(null);
  const [screenWidth, setScreenWidth] = useState(
    Dimensions.get('window').width,
  );
  const [screenHeight, setScreenHeight] = useState(
    Dimensions.get('window').height,
  );
  const scale = (size, wd, ht) => (size / 1404) * (wd > ht ? ht : wd);

  useEffect(() => {
    const handleDimensionsChange = ({window: {width, height}}) => {
      setScreenWidth(width);
      setScreenHeight(height);
      console.log(width, height, 'width, heightwidth, height');
    };
    Dimensions.addEventListener('change', handleDimensionsChange);
  }, []);
  useEffect(() => {
    _getStickerGroupList();
  }, []);

  /*
   * 查询全部的贴纸库
   * */
  const _getStickerGroupList = async () => {
    try {
      const {data} = await StickerDataSQL.db_fun(
        DB_ST.SELECT_STICKER_GROUP_UPDATE_ST,
        [],
      );
      console.log(data, 'setStickerGroupsetStickerGroup');
      setStickerGroups([
        {id: 'new_create_group', name: i18n.t('title.newColl')},
        ...data,
      ]);
      if (data?.length > 0) {
        const res = await renameFunGroup(
          i18n.t('title.newColl') + ' 1_sticker',
          DB_ST.SELECT_NAME_ST,
        );
        setStickerName(res);
        setStickerGroup(data[0]);
      } else {
        setStickerName(i18n.t('title.newColl') + ' 1_sticker 1');
        setStickerGroup({
          id: 'new_create_group',
          name: i18n.t('title.newColl'),
        });
      }
    } catch (error) {
      console.error('Error fetching sticker groups:', error);
    }
  };

  /*
   *添加贴纸库
   * */
  const _stickerGroupAdd = async groupName => {
    const {code, data} = await stickerGroupAdd(groupName);
    console.log(data, 'addDataaddDataaddDataaddData');
    if (code === 200) {
      const makeDir = await NativeFileUtils.makeDir(data?.path);
      console.log(makeDir, 'makeDirmakeThDir');
      setStickerGroup({
        name: groupName,
        path: data?.path,
        thumb_sticker: '',
        id: data?.id,
      });
      setModalVisible(false);
      if (
        stickerGroups?.filter(item => item?.id !== 'new_create_group')?.length <
        1
      ) {
        _saveSticker(data);
      } else {
        await _getStickerGroupList();
        return {
          name: groupName,
          path: data?.path,
          thumb_sticker: '',
          id: data?.id,
        };
      }
    }
  };

  const _saveSticker = async (data = null) => {
    try {
      const res = await saveSticker(
        data || stickerGroup,
        stickerName || stickerDefaultName,
      );
      if (res) {
        setStickerName('');
        setStickerDefaultName('');
        await StickerDataSQL.db_fun(DB_ST.UPDATE_GROUP_STICKER_UPDATE_ST, [
          Date.now(),
          stickerGroup?.id,
        ]);
        await _getStickerGroupList();
        await NativeEvent.onStop();
      }
    } catch (e) {
      console.log(e);
    }
  };
  const _onItemPress = async item => {
    if (item.id === 'new_create_group') {
      if (stickerGroups?.length > 49) {
        return;
      }
      setStickerGroup(item);
      setModalVisible(true);
    } else {
      const {code, data} = await StickerDataSQL.db_fun(
        DB_ST.SELECT_STICKER_GROUP_ID_ST,
        [item?.id],
      );
      if (data?.length > 199) {
        return;
      } else {
        setStickerGroup(item);
        setStickerDefaultName(
          findNextEm(data, item?.name + '_sticker', ite => ite.name),
        );
      }
    }
  };

  return (
    <View style={styles.container}>
      <TitleBar
        backgroundColor={'#000'}
        textColor={'#fff'}
        textRightColor={'#999'}
        leftBtnText={i18n.t('btn.cancel')}
        onBack={async () => {
          changeEvent();
          await NativeEvent.onStop();
        }}
        title={i18n.t('title.newSt')}
        rightBtnText={i18n.t('btn.create')}
        status={'create'}
        rightBtnStatus={true}
        screenWidth={screenWidth}
        screenHeight={screenHeight}
        rightValueBtn={stickerName || stickerDefaultName ? true : false}
        onRight={async () => {
          if (
            stickerGroups?.filter(item => item?.id !== 'new_create_group')
              ?.length < 1
          ) {
            console.log(stickerName, 'stickerGroupstickerGroup');
            await _stickerGroupAdd(stickerGroup?.name + ' 1');
          } else {
            await _saveSticker();
          }
          setStickerGroup(null);
          setStickerName('');
          setStickerDefaultName('');
          Keyboard.dismiss();
          console.log(stickerGroup, 'stickerGroupstickerGroup');
        }}
      />
      <View
        style={{
          width: screenWidth,
          height: scale(
            screenWidth > screenHeight ? 1290 : 1758,
            screenWidth,
            screenHeight,
          ),
          padding: scale(48, screenWidth, screenHeight),
        }}>
        <View
          style={{
            height: scale(200, screenWidth, screenHeight),
            borderBottomColor: '#000',
            borderBottomWidth: scale(2, screenWidth, screenHeight),
            borderStyle: 'dotted',
          }}>
          <Text
            style={{
              fontSize: scale(34, screenWidth, screenHeight),
              color: '#000',
              marginBottom: scale(20, screenWidth, screenHeight),
              fontWeight: '700',
            }}>
            {i18n.t('btn.name')}
          </Text>
          <View
            style={{
              height: scale(88, screenWidth, screenHeight),
            }}>
            <TextInput
              style={{
                height: scale(88, screenWidth, screenHeight),
                fontSize: scale(34, screenWidth, screenHeight),
                fontWeight: '400',
                color: '#000',
                borderWidth: scale(2, screenWidth, screenHeight),
                borderColor: '#000',
                paddingLeft: scale(20, screenWidth, screenHeight),
                paddingRight: scale(100, screenWidth, screenHeight),
              }}
              selectTextOnFocus={false}
              // maxLength={150}
              placeholder={i18n.t('placeholder.sticker')}
              onChangeText={setStickerName}
              defaultValue={stickerName || stickerDefaultName}
              onBlur={() => Keyboard.dismiss()}
            />
          </View>
          {stickerName ? (
            <TouchableWithoutFeedback onPress={() => setStickerName('')}>
              <Image
                style={{
                  position: 'absolute',
                  right: scale(24, screenWidth, screenHeight),
                  width: scale(48, screenWidth, screenHeight),
                  height: scale(48, screenWidth, screenHeight),
                  top: scale(88, screenWidth, screenHeight),
                }}
                source={require('../../assets/ic_close.png')}
              />
            </TouchableWithoutFeedback>
          ) : null}
        </View>
        <View
          style={[
            styles.flexCenterSpace,
            {marginTop: scale(48, screenWidth, screenHeight)},
          ]}>
          <Text
            style={{
              fontSize: scale(34, screenWidth, screenHeight),
              fontWeight: '400',
              color: '#000',
            }}>
            {i18n.t('title.coll')}
          </Text>
          {stickerGroups?.length > 8 ? (
            <TouchableWithoutFeedback
              onPress={() => setModalStickerVisible(true)}>
              <View style={styles.flexCenter}>
                <Text
                  style={{
                    fontSize: scale(26, screenWidth, screenHeight),
                    fontWeight: '700',
                    marginRight: scale(12, screenWidth, screenHeight),
                  }}>
                  {i18n.t('btn.viewAll')}
                </Text>
                <Image
                  style={{
                    width: scale(32, screenWidth, screenHeight),
                    height: scale(32, screenWidth, screenHeight),
                  }}
                  source={require('../../assets/ic_arrow_right.png')}
                />
              </View>
            </TouchableWithoutFeedback>
          ) : null}
        </View>
        <FlatListTm
          list={stickerGroups.slice(0, 8)}
          onItemPress={item => _onItemPress(item)}
          screenWidth={screenWidth}
          screenHeight={screenHeight}
          bodyStyle={{
            width: screenWidth,
            height: scale(
              screenWidth > screenHeight ? 898 : 1366,
              screenWidth,
              screenHeight,
            ),
          }}
          checkId={stickerGroup}
          itemStyle={{
            width: scale(206, screenWidth, screenHeight),
            marginRight: scale(
              screenWidth > screenHeight ? 81.6 : 120,
              screenWidth,
              screenHeight,
            ),
            marginBottom: scale(74, screenWidth, screenHeight),
            justifyContent: 'center',
            alignItems: 'center',
          }}
          status={'create'}
        />
      </View>
      <ModalSelectSticker
        modalVisible={modalStickerVisible}
        data={stickerGroups?.filter(item => item?.id !== 'new_create_group')}
        screenWidth={screenWidth}
        screenHeight={screenHeight}
        onClose={() => {
          setModalStickerVisible(false);
        }}
        checkId={stickerGroup}
        onConfirm={async item => {
          // _onItemPress(item);
          const {code, data} = await StickerDataSQL.db_fun(
            DB_ST.SELECT_STICKER_GROUP_ID_ST,
            [item?.id],
          );
          setStickerGroup(item);
          setStickerDefaultName(
            findNextEm(data, item?.name + '_sticker', ite => ite.name),
          );
          setModalStickerVisible(false);
        }}
      />
      <ModalCreateGroup
        title={i18n.t('title.newColl')}
        placeholder={i18n.t('placeholder.group')}
        btnOk={i18n.t('btn.create')}
        modalVisible={modalVisible}
        screenWidth={screenWidth}
        screenHeight={screenHeight}
        onClose={() => setModalVisible(false)}
        onConfirm={async nm => {
          setModalVisible(false);
          _stickerGroupAdd(nm);
        }}
        value={''}
        status={1}
      />
    </View>
  );
};

export default StickerCreatePage;
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    flex: 1,
  },
  flexCenter: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  flexCenterSpace: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
});
